#!/usr/bin/ruby

require "net/telnet.rb"

class ImapTester 

  attr :imap
  attr :msgCounter

  attr :response

  attr :show

  def initialize(port = 10142, host = "localhost", username = nil, password = nil)
	@imap = Net::Telnet::new("Host" => host,
                         "Port" => port,
                         "Telnetmode" => false,
#/([01234569])* *OK.*completed./
#                         "Prompt" => /(([01234569])* *OK.*completed\.|ready)\n/,
                     #    "Prompt" => /(completed\.|Server.*ready.*)\n/,
                        "Prompt" => /y\n/,
			"Binmode" => true,
			"Timeout" => 60,
			"Output_log" => "telnet.dump"
  	);
	@msgCounter = 1;
	if (username!=nil and password!=nil)
          login(username,password)
        end
        @show = true;
  end

  def login(username, password) 
 #    @imap.cmd("String" => "x noop", "Prompt" => /Server.*ready/)
     sendmsg "login #{username} #{password}";
     waitfor("completed.")
  end

  def create_mailbox(mx) 
    getresponse "create #{mx}"
  end

  def dir
    getresponse "list \"#\" \"*\""
  end

  def sendmsg(msg) 
   print "send msg #{@msgCounter} #{msg}\n"
   @imap.puts("#{@msgCounter} #{msg}\r")
   @msgCounter = @msgCounter + 1; 
  end

  def current_regexp
    Regexp.new("#{@msgCounter} (OK.*completed)|(BAD.*command)|(NO.*)");
  end

  def getresponse(msg) 
#   @imap.cmd("#{@msgCounter} #{msg}") { |c| @response << c }
   print "getresponse #{@msgCounter} #{msg}\n"
   @imap.puts("#{@msgCounter} #{msg}\r");
   waitfor(current_regexp);
   @msgCounter = @msgCounter + 1; 
   @response
  end

  def waitfor(msg) 
    r = Regexp.new(msg)
    @response = []
    @imap.waitfor(r) { |c|
        if @show
          print "S:#{c}\n" 
        end 
	response << c }
#    print "WAITFOR RESP: #{@response}\n"
  end

  def logout
    sendmsg("logout");
  end

  def checkMailboxExists(mb)
    getresponse("list \"\" \"#{mb}\"")
    if (@response.length > 1) 
#* LIST () "." Trash
      return Regexp.new("LIST.*#{mb}").match(@response[0])!=nil
    end
    return false
    #@response.length.times { |c| print "line[#{c}] : #{@response[c]}\n" }
  end

  def checkInbox
    getresponse("select INBOX")
  end


  def body(uin)
    getresponse("UID fetch #{uin} (UID BODY.PEEK[HEADER.FIELDS (From To Cc Subject Date Message-ID)] BODY.PEEK[TEXT])");
  end

  def header(uin)
    getresponse("UID fetch #{uin} (UID BODY.PEEK[HEADER.FIELDS (From To Cc Subject Date Message-ID)])");
  end

  def list
    getresponse("UID fetch 1:* (UID BODY.PEEK[HEADER.FIELDS (From To Cc Subject Date Message-ID)])");
  end

  def saveDraft(folderName, mailContent, messageId) 
    mbox = getresponse("select \"#{folderName}\"");
    mailContent = mailContent.gsub("RANDOM_MESSAGE_ID", messageId)
    appendResult = getresponse("append \"#{folderName}\" (\\Draft \\Seen) {#{mailContent.length}+}\r\n#{mailContent}");
    noopRes = getresponse("noop")
    searchRes = getresponse("uid SEARCH UNDELETED HEADER Message-ID #{messageId}");
  end

  def saveFileToDraft(folderName, fileName, messageId) 
    saveDraft(folderName, File.open(fileName).read, messageId )
  end

  def testSearch() 
    getresponse("uid SEARCH UNDELETED HEADER Message-ID 604921928@terminus.euedge.com");
  end


  def select(mb) 
    getresponse("select \"#{mb}\"");
  end 
 
  def testSaveDraft() 
    saveFileToDraft("Drafts", "test/testmail.txt", "#{Kernel.rand * 100000}@terminus.euedge.com")
  end

  def thundermailCheck(uin) 
    flgs = getresponse("UID fetch #{uin} (FLAGS)");
    headers = getresponse("UID fetch #{uin} (UID RFC822.SIZE FLAGS BODY.PEEK[HEADER.FIELDS (From To Cc Subject Date Message-ID Priority X-Priority References Newsgroups In-Reply-To Content-Type)])")
    peek = getresponse("UID fetch #{uin} (UID BODY.PEEK[HEADER.FIELDS (Content-Type Content-Transfer-Encoding)] BODY.PEEK[TEXT]<0.2048>)");
  end

end


#46C1B278.5050001@terminus.euedge.com
def init() 
	tester = ImapTester.new();
	tester.login("zsombor","zsombor");
	tester
end

##tester.sendmsg("select inbox");

#if (tester.checkMailboxExists("Trash")) 
#  print "Trash found.\n";
#end
#if (not tester.checkMailboxExists("TrashX")) 
#  print "TrashX NOT found.\n";
#end

#tester.switchMailbox("Drafts")
#tester.testSearch();

#tester.saveFileToDraft("Drafts", "test/testmail.txt", "#{tester.hash.abs}@terminus.euedge.com")
#tester.logout;

#imap.cmd("1 login zsombor zsombor") { |c| print c }
# imap.cmd("2 select inbox") { |c| print c }
#imap.cmd("3 select Drafts") { |c| print c }
#imap.cmd("4 logout") { |c| print c }


